package com.m3958.firstgwt.server.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.service.MySHAService;

@Singleton
public class YuiCombServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	private MySHAService shaService;
	
	private Map<String, String> comboyui = new HashMap<String, String>();
	
	private Map<String, String> shaMap = new HashMap<String, String>();
	
	@Inject
	private AppUtilService autils;
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		//?3.4.1/build/yui-base/yui-base-min.js&3.4.1/build/oop/oop-min.js//顺序相关。
		StringBuffer qsbuf = new StringBuffer();
		String qs = req.getQueryString();//调试模式下是null，服务器一侧不可能null。
		String version = req.getParameter("version");
		String appendMinJs = req.getParameter("appendminjs");
		String type = req.getParameter("type");
		String[] fns = new String[]{};
		
		if(qs != null)
			fns = qs.split("&");
		if(appendMinJs != null){
			type = "js";
		}
		for(String fn :fns){
			if(fn.startsWith("hostname=") || fn.startsWith("remoteip=") || fn.equals("version") || fn.equals("appendminjs") || fn.equals("type")){
				;
			}else{
				qsbuf.append(fn).append("&");
			}
		}
		String finalqs = qsbuf.toString();
		
		if(finalqs.isEmpty()){
			finalqs = req.getRequestURI().replace("/yuicombo", "/yui");
			fns = new String[]{finalqs};
		}
		
		
		String etag = req.getHeader("If-None-Match");
		if(etag != null && etag.equals(shaMap.get(finalqs))){
			res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
			return;
		}
		String outstr = comboyui.get(finalqs);
	
		if(outstr == null){
			File rootf;
			if(version != null){
				 rootf = new File(getServletContext().getRealPath("/yui"),version + "/build/");
			}else{
				rootf = new File(getServletContext().getRealPath("/yui"));
			}
			File wr = new File(getServletContext().getRealPath("/"));
			StringBuffer sb = new StringBuffer();
			
			for(String fn : fns){
				File f = null;
				if(fn.startsWith("/")){
					f = new File(wr,fn);
				}else{
					if(appendMinJs != null && !fn.endsWith("min.js")){
						f = new File(rootf,fn + "-min.js");
					}else{
						f = new File(rootf,fn);
					}
				}
				if(f != null && f.isFile() && f.exists()){
					try {
						FileInputStream is = new FileInputStream(f);
						sb.append(autils.read2String(is, "utf-8"));
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
					
			}
			outstr =  sb.toString();
			if(outstr.length() > 20){
				comboyui.put(finalqs,outstr);
				shaMap.put(finalqs, shaService.encrypt(outstr));
			}
		}
		if("css".equals(type)){
			type = "text/css";
		}else{
			type = "application/javascript";
		}
		res.setContentType(type + ";charset=utf-8");   
		res.setCharacterEncoding("UTF-8");
		res.setHeader("Etag", shaMap.get(finalqs));
		Writer out = res.getWriter();
		out.write(comboyui.get(finalqs));
		out.flush();
		out.close();
	}
}
